package com.easygem.front.service.imp;

import com.easygem.common.model.front.CallLog;
import com.easygem.common.vo.front.CallLogVo;
import com.easygem.common.vo.front.SeatTrafficVo;
import com.easygem.common.vo.system.PageVO;
import com.easygem.front.mapper.CallLogMapper;
import com.easygem.front.mapper.DepartmentMapper;
import com.easygem.front.service.CallLogService;
import com.easygem.front.service.base.AbstractServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author luoxi
 * @version 1.0
 * @className CallLogServiceImpl
 * @Description 话单日志业务层接口的实现
 * @date 2025/2/19 08:42
 */
@Service
public class CallLogServiceImpl extends AbstractServiceImpl<CallLogMapper, CallLog, Integer> implements CallLogService {
    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private CallLogMapper callLogMapper;

    /**
     * 通过条件查询话单日志信息
     *
     * @param pageNum   页码
     * @param pageSize  页面数
     * @param callLogVo 条件对象
     * @return
     */
    @Override
    public PageVO<CallLog> findList(Integer pageNum, Integer pageSize, CallLogVo callLogVo) {
        CallLog callLog = new CallLog();
        BeanUtils.copyProperties(callLogVo, callLog);
        PageHelper.startPage(pageNum, pageSize);
        List<CallLog> callLogs = callLogMapper.getCallLogList(callLog);
        for (CallLog callLog1 : callLogs) {
            if (callLog1.getDuration() == null) {
                callLog1.setConsumptionAmount(null);
            } else {
                //计算消费金额，保留两位小数点
                callLog1.setConsumptionAmount( Double.parseDouble(String.format("%.2f", callLog1.getCircuitTariff()*callLog1.getDuration())));
            }
        }
        PageInfo<CallLog> info = new PageInfo<>(callLogs);
        return new PageVO<>(info.getTotal(), callLogs);
    }

    /**
     * 批量导出话单记录
     *
     * @param logId 话单id集合
     * @return 话单列表
     */
    @Override
    public List<CallLog> downExcelBatch(List<Long> logId) {
        return callLogMapper.downExcelBatch(logId);
    }

    /**
     * 通过条件查出话单记录,用于导出
     *
     * @param callLogVo
     * @return
     */
    @Override
    public List<CallLog> downExcelAll(CallLogVo callLogVo) {
        CallLog callLog = new CallLog();
        BeanUtils.copyProperties(callLogVo, callLog);
        return callLogMapper.getCallLogList(callLog);
    }


    /**
     * 通过条件查询话单日志信息
     *
     * @param callLogVo 条件对象
     * @return 用于坐席话务统计
     */
    @Override
    public PageVO<SeatTrafficVo> getCallLogListByCallLog(Integer pageNum, Integer pageSize, CallLogVo callLogVo) {
        List<SeatTrafficVo> seatTrafficVos = new ArrayList<>();
        CallLog callLog = new CallLog();
        BeanUtils.copyProperties(callLogVo, callLog);
        List<Long> userIds = callLogMapper.getUserByAccountAndDeptId(callLog);
        for (Long callLog1 : userIds) {
            callLog.setUserId(callLog1);
            SeatTrafficVo seatTrafficVo = getSeatTraffic(callLog);
            // 判断 seatTrafficVo 不为空时才添加到集合中
            if (seatTrafficVo != null) {
                seatTrafficVos.add(seatTrafficVo);
            }
            //页面显示判断
            if (seatTrafficVos.size() == pageNum * pageSize) {
                break;
            }
        }
        return new PageVO<>(seatTrafficVos.size(), seatTrafficVos);
    }

    /**
     * 用于计算一个坐席下的话单记录
     *
     * @param callLog 条件对象
     * @return
     */

    public SeatTrafficVo getSeatTraffic(CallLog callLog) {
        List<CallLog> callLogs = callLogMapper.getCallLogListByCallLog(callLog);
        if (callLogs.isEmpty()) {
            return null;
        }
        SeatTrafficVo seatTrafficVo = new SeatTrafficVo();
        for (CallLog callLog1 : callLogs) {
            if (seatTrafficVo.getUserId() == null) {
                seatTrafficVo.setUserId(callLog1.getUserId());
            }
            if (seatTrafficVo.getUserName() == null) {
                seatTrafficVo.setUserName(callLog1.getUserName());
            }
            if (seatTrafficVo.getNickName() == null) {
                seatTrafficVo.setNickName(callLog1.getNickName());
            }
            if (seatTrafficVo.getDeptName() == null) {
                seatTrafficVo.setDeptName(callLog1.getDeptName());
            }
            if (seatTrafficVo.getUserName() == null) {
                seatTrafficVo.setUserName(callLog1.getUserName());
            }

            //通话数，当 callNum 为 null 则使用 1 作为初始值，否则加一
            seatTrafficVo.setCallNum(Optional.ofNullable(seatTrafficVo.getCallNum()).map(num -> num + 1).orElse(1));

            if (callLog1.getStatus() != null && callLog1.getStatus().equals("1")) {//判断通话是否接通
                //通话成功数,当 callSuccess 为 null 则使用 1 作为初始值，否则加一
                seatTrafficVo.setCallSuccess(Optional.ofNullable(seatTrafficVo.getCallSuccess()).map(num -> num + 1).orElse(1));
                //通话总时长
                seatTrafficVo.setCallTotalDuration(Optional.ofNullable(seatTrafficVo.getCallTotalDuration()).map(num -> num + callLog1.getSecondsDuration()).orElse(callLog1.getSecondsDuration()));
                //计费时长
                seatTrafficVo.setBillingDuration(Optional.ofNullable(seatTrafficVo.getBillingDuration()).map(num -> num + callLog1.getDuration()).orElse(callLog1.getDuration()));
            }
            //呼出数,当 exhaleNum 为 null 则使用 1 作为初始值，否则加一
            seatTrafficVo.setExhaleNum(Optional.ofNullable(seatTrafficVo.getExhaleNum()).map(num -> num + 1).orElse(1));

            if (callLog1.getStartTime() != null && callLog1.getEndTime() != null) {
                //呼出成功数,当 exhaleSuccess 为 null 则使用 1 作为初始值，否则加一
                seatTrafficVo.setExhaleSuccess(Optional.ofNullable(seatTrafficVo.getExhaleSuccess()).map(num -> num + 1).orElse(1));
                // 解析通话开始时间，将其转换为毫秒数
                long start = callLog1.getStartTime().getTime();
                // 解析通话结束时间，将其转换为毫秒数
                long end = callLog1.getEndTime().getTime();
                // 计算通话时长（毫秒）
                long duration = end - start;
                // 将毫秒转换为秒
                int seconds = (int) (duration / 1000);
                // 累加呼出总时长
                seatTrafficVo.setExhaleTotalDuration(Optional.ofNullable(seatTrafficVo.getExhaleTotalDuration()).map(num -> num + seconds).orElse(seconds));
            }
        }
        // 通话成功率
        if (seatTrafficVo.getCallNum() != null && seatTrafficVo.getCallSuccess() != null) {
            seatTrafficVo.setCallSuccessRate(String.format("%.2f%%", seatTrafficVo.getCallSuccess() * 1.0 / seatTrafficVo.getCallNum() * 100));
        }
        // 通话平均时长
        if (seatTrafficVo.getCallSuccess() != null && seatTrafficVo.getCallTotalDuration() != null) {
            seatTrafficVo.setCallAverageDuration(seatTrafficVo.getCallTotalDuration() / seatTrafficVo.getCallSuccess());
        }
        // 呼出成功率
        if (seatTrafficVo.getExhaleNum() != null && seatTrafficVo.getExhaleSuccess() != null) {
            seatTrafficVo.setExhaleSuccessRate(String.format("%.2f%%", seatTrafficVo.getExhaleSuccess() * 1.0 / seatTrafficVo.getExhaleNum() * 100));
        }
        // 呼出平均通话时长
        if (seatTrafficVo.getExhaleSuccess() != null && seatTrafficVo.getExhaleTotalDuration() != null) {
            seatTrafficVo.setExhaleAverageDuration(seatTrafficVo.getExhaleTotalDuration() / seatTrafficVo.getExhaleSuccess());
        }
        return seatTrafficVo;
    }

    /**
     * 批量导出坐席话务统计记录
     *
     * @param callLogVo 条件对象
     * @return 话单列表
     */
    @Override
    public List<SeatTrafficVo> seatTrafficDownExcelBatch(CallLogVo callLogVo) {
        List<SeatTrafficVo> seatTrafficVos = new ArrayList<>();
        CallLog callLog = new CallLog();
        BeanUtils.copyProperties(callLogVo, callLog);
        callLog.setNickNameId(null);//防止多条件判断
        callLog.setDeptNameId(null);//防止多条件判断
        for (Long userId : callLog.getUserIds()) {
            callLog.setUserId(userId);
            SeatTrafficVo seatTrafficVo = getSeatTraffic(callLog);
            // 判断 seatTrafficVo 不为空时才添加到集合中
            if (seatTrafficVo != null) {
                seatTrafficVos.add(seatTrafficVo);
            }
        }
        return seatTrafficVos;
    }

    /**
     * 通过条件查出坐席话务统计记录,用于导出
     *
     * @param callLogVo
     * @return
     */
    @Override
    public List<SeatTrafficVo> seatTrafficDownExcelAll(CallLogVo callLogVo) {
        List<SeatTrafficVo> seatTrafficVos = new ArrayList<>();
        CallLog callLog = new CallLog();
        BeanUtils.copyProperties(callLogVo, callLog);
        List<Long> userIds = callLogMapper.getUserByAccountAndDeptId(callLog);
        for (Long callLog1 : userIds) {
            callLog.setUserId(callLog1);
            SeatTrafficVo seatTrafficVo = getSeatTraffic(callLog);
            // 判断 seatTrafficVo 不为空时才添加到集合中
            if (seatTrafficVo != null) {
                seatTrafficVos.add(seatTrafficVo);
            }
        }
        return seatTrafficVos;
    }


}
